package vsm.vsm_server.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import vsm.vsm_server.mapper.LikeMapper;
import vsm.vsm_server.pojo.Notice.Notice;
import vsm.vsm_server.pojo.User.Record.History.UserVideoHistoryDTO;
import vsm.vsm_server.pojo.User.Record.Like.LikeVideo;
import vsm.vsm_server.pojo.User.Record.Like.UserVideoIsLikeDTO;
import vsm.vsm_server.pojo.Video.Video;
import vsm.vsm_server.pojo.Video.VideoNailVO;
import vsm.vsm_server.pojo.Video.VideoUrlVO;
import vsm.vsm_server.service.*;

import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class LikeServiceImpl implements LikeService {
    private LikeMapper likeMapper;

    public LikeServiceImpl(LikeMapper likeMapper){
        this.likeMapper=likeMapper;
    }


    @Autowired
    VideoService videoService;
    @Autowired
    VodService vodService;
    @Autowired
    NoticeService noticeService;
    @Autowired
    ActionService actionService;
    @Override
    public List<VideoNailVO> getLikeVideos(BigInteger userId) {
        List<VideoNailVO> videoNailVOList = new ArrayList<>();
        List<LikeVideo> likeVideoList =  likeMapper.getLikeVideos(userId);
        if(likeVideoList!=null){
            for(LikeVideo v:likeVideoList){
                //根据videoId获取video信息
                Video video = videoService.getVideo(v.getVideoId());
                //根据video信息赋值给videoNail
                VideoNailVO newVideoNailVO = new VideoNailVO();
                BeanUtils.copyProperties(video, newVideoNailVO);
                //获取到videoNail其他值
                VideoUrlVO newVideoUrlVO = vodService.getUrl(newVideoNailVO.getPath());
                BeanUtils.copyProperties(newVideoUrlVO, newVideoNailVO);
                //将videoNail放入列表
                videoNailVOList.add(newVideoNailVO);
            }
        }
        return videoNailVOList;


    }

    @Override
    public Boolean isLikeVideo(LikeVideo likeVideo) {
        return likeMapper.isLikeVideo(likeVideo);
    }

    @Override
    public void likeVideo(LikeVideo likeVideo) {
        //保存记录
        Notice notice = new Notice();
        notice.setType(1);
        String datestr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        notice.setTime(datestr);
        BigInteger videoId = likeVideo.getVideoId();
        BigInteger creatorId = videoService.getUserId(videoId);
        notice.setVideoId(videoId);
        notice.setUserId(creatorId);
        notice.setSenderId(likeVideo.getUserId());
        notice.setContent("点赞了你的视频");
        noticeService.saveNotice(notice);
        likeMapper.likeVideo(likeVideo);

        //记录行为
        actionService.LikeVideo(likeVideo);
    }

    @Override
    public void unlikeVideo(LikeVideo likeVideo) {
        likeMapper.unlikeVideo(likeVideo);
    }

    @Override
    public List<UserVideoIsLikeDTO> isLikeVideoList(List<UserVideoHistoryDTO> historyList) {
        if (historyList == null || historyList.isEmpty()) {
            log.info("Input historyList is empty, returning empty list for like status check.");
            return Collections.emptyList();
        }

        // 1. 过滤掉无效的输入项 (userId 或 videoId 为 null)
        //    同时，为了 Set 能够工作，我们需要确保 UserVideoHistoryDTO 也正确实现了 equals 和 hashCode
        //    或者，我们可以只传递有效的 pair 列表给 Mapper
        List<UserVideoHistoryDTO> validPairs = historyList.stream()
                .filter(dto -> dto != null && dto.getUserId() != null && dto.getVideoId() != null)
                // 可选：如果 historyList 可能包含重复的 (userId, videoId) 对，可以在这里去重
                // .distinct() // 需要 UserVideoHistoryDTO 实现 equals/hashCode
                .collect(Collectors.toList());

        if (validPairs.isEmpty()) {
            log.info("No valid (userId, videoId) pairs found in the input list.");
            return Collections.emptyList();
        }

        // 2. 【关键】调用 Mapper 方法，获取在 videolikes 表中实际存在的 (userId, videoId) 对的 Set
        Set<LikeVideo> existingLikesSet; // 注意：这个 Set 只包含点赞过的记录

        try {
            // 调用我们之前修正好的 Mapper 方法
            existingLikesSet = likeMapper.findExistingLikesInBatch(validPairs);
            if (existingLikesSet == null) {
                existingLikesSet = Collections.emptySet();
            }
            log.debug("Found {} existing like records from DB.", existingLikesSet.size());
        } catch (Exception e) {
            log.error("Error querying existing likes in batch: {}", e.getMessage(), e);
            return Collections.emptyList(); // 查询失败返回空
        }

        // 3. 遍历【原始的有效输入列表 validPairs】，构建最终结果 List<UserVideoIsLikeDTO>
        List<UserVideoIsLikeDTO> resultList = new ArrayList<>();
        for (UserVideoHistoryDTO historyDto : validPairs) {
            UserVideoIsLikeDTO resultDto = new UserVideoIsLikeDTO();
            resultDto.setUserId(historyDto.getUserId());
            resultDto.setVideoId(historyDto.getVideoId());

            // 创建一个【临时的 VideoLikeSimpleDto】用于在 Set 中查找
            // 这个临时对象只需要 userId 和 videoId
            LikeVideo checkPair = new LikeVideo(historyDto.getUserId(), historyDto.getVideoId());

            // 【核心判断】检查这个 (userId, videoId) 对是否存在于从数据库查出来的点赞集合中
            boolean liked = existingLikesSet.contains(checkPair); // 利用 Set 的 contains (O(1))

            resultDto.setIsLike(liked ? Boolean.TRUE : Boolean.FALSE); // 根据是否存在设置 isLike

            resultList.add(resultDto);
        }

        log.debug("Generated like status list with {} entries.", resultList.size());
        return resultList;
    }
}
